package com.webchat.chat.service.impl;

import com.google.common.collect.Lists;
import com.webchat.chat.core.AbstractService;
import com.webchat.chat.core.dto.loginDto.MenuReturnDTO;
import com.webchat.chat.core.tools.ChatConstant;
import com.webchat.chat.dao.PermissionMapper;
import com.webchat.chat.model.Permission;
import com.webchat.chat.service.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * Created by admin on 2018-06-29.
 */
@Service
@Transactional
public class PermissionServiceImpl extends AbstractService<Permission> implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public Collection<? extends String> findPermissionCodeByUserId(String userId) {
        return permissionMapper.findPermissionCodeByUserId(userId);
    }

    @Override
    public List<MenuReturnDTO> findAllMenuByUserId(String userId) {
        List<Permission> allMenus = permissionMapper.findAllMenuByUserId(userId);
        List<MenuReturnDTO> menus = genMenuTree(allMenus, Lists.newArrayList(), ChatConstant.ROOT_MENU_ID);
        Collections.sort(menus, (o1, o2) -> {
            if (o1.getSort() == o2.getSort()) {
                return 0;
            } else if (o1.getSort() > o2.getSort()) {
                return 1;
            }
            return -1;
        });
        menus.forEach(parentMenu -> {
            Collections.sort(parentMenu.getChildren(), (o1, o2) -> {
                if (o1.getSort() == o2.getSort()) {
                    return 0;
                } else if (o1.getSort() > o2.getSort()) {
                    return 1;
                }
                return -1;
            });
        });
        return menus;
    }

    @Override
    public List<Permission> findPermissionTree() {
        //所有的菜单
        List<Permission> allPerm = permissionMapper.selectAll();
        //根节点
        List<Permission> rootPerm = new ArrayList<>();
        for (Permission perm : allPerm) {
            if (perm.getParentPermissionId().equals("0")) { //父节点为0的是根节点
                rootPerm.add(perm);
            }
        }
        Collections.sort(rootPerm, order());
        for (Permission perm : rootPerm) {
            List<Permission> childList = getChild(perm.getId(), allPerm);
            perm.setChildren(childList);
        }

        return rootPerm;

    }

    @Override
    public void deletePermission(String id) {
        List<Permission> permissions = permissionMapper.selectByIds(id);
        permissions.forEach(p -> {
            p.setIsDisplay(false);
            permissionMapper.updateByPrimaryKey(p);
        });
    }

    /**
     * 排序,根据order排序
     */
    public Comparator<Permission> order() {
        Comparator<Permission> comparator = new Comparator<Permission>() {
            @Override
            public int compare(Permission o1, Permission o2) {
                if (o1.getSort() != o2.getSort()) {
                    return o1.getSort() - o2.getSort();
                }
                return 0;
            }
        };
        return comparator;
    }

    public List<Permission> getChild(String id, List<Permission> allPerm) {
        //子菜单
        List<Permission> childList = new ArrayList<>();
        for (Permission perm : allPerm) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (perm.getParentPermissionId().equals(id)) {
                childList.add(perm);
            }
        }
        //递归
        for (Permission perm : childList) {
            perm.setChildren(getChild(perm.getId(), allPerm));
        }
        Collections.sort(childList, order());//排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<Permission>();
        }
        return childList;
    }


    private List<MenuReturnDTO> genMenuTree(List<Permission> allMenus, List<MenuReturnDTO> menus, String parentMenuId) {
        if (allMenus == null || allMenus.isEmpty()) {
            return menus;
        }
        allMenus.forEach(menu -> {
            if (Objects.equals(menu.getParentPermissionId(), parentMenuId)) {
                MenuReturnDTO menuReturnDTO = new MenuReturnDTO();
                menuReturnDTO.setIcon(menu.getIcon());
                menuReturnDTO.setMenuName(menu.getPermissionName());
                menuReturnDTO.setPath(menu.getPath());
                menuReturnDTO.setSort(menu.getSort());
                //递归查找子集
                List<MenuReturnDTO> subMenu = genMenuTree(allMenus, Lists.newArrayList(), menu.getId());
                menuReturnDTO.setChildren(subMenu);
                menus.add(menuReturnDTO);
            }
        });

        return menus;
    }
}
